package com.draven.mall.service.impl;

import com.draven.mall.entity.Admin;
import com.draven.mall.service.AdminService;
import org.springframework.stereotype.Service;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.*;

/**
 * 管理员服务实现类
 */
@Service
public class AdminServiceImpl implements AdminService {

    // 模拟管理员数据，实际应用中应该从数据库读取
    private static final Map<String, Admin> ADMIN_MAP = new HashMap<>();
    private static final Map<String, Admin> TOKEN_MAP = new HashMap<>();

    private final JdbcTemplate jdbcTemplate;

    public AdminServiceImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    static {
        // 初始化一个管理员账号
        Admin admin = new Admin();
        admin.setId(1L);
        admin.setUsername("admin");
        admin.setPassword("admin123"); // 实际应用中应该加密存储
        admin.setName("系统管理员");
        admin.setStatus(1);
        admin.setCreateTime(new Date());
        
        ADMIN_MAP.put(admin.getUsername(), admin);
    }

    @Override
    public Admin login(String username, String password) {
        Admin admin = ADMIN_MAP.get(username);
        
        if (admin != null && admin.getPassword().equals(password) && admin.getStatus() == 1) {
            return admin;
        }
        
        return null;
    }

    @Override
    public Admin getAdminByToken(String token) {
        // 实际应用中应该解析token，这里简化处理
        // 模拟从token中获取管理员信息
        if (token != null && token.startsWith("admin-token-")) {
            return ADMIN_MAP.get("admin");
        }
        return null;
    }

    @Override
    public Admin getAdminById(Long id) {
        // 遍历查找管理员
        for (Admin admin : ADMIN_MAP.values()) {
            if (admin.getId().equals(id)) {
                return admin;
            }
        }
        return null;
    }

    @Override
    public Map<String, Object> getDashboardData() {
        Map<String, Object> data = new HashMap<>();
        
        // 从数据库查询商家数量
        try {
            // 查询商家总数
            String merchantSql = "SELECT COUNT(*) FROM tb_merchant";
            Integer merchantCount = jdbcTemplate.queryForObject(merchantSql, Integer.class);
            data.put("merchantCount", merchantCount);
            
            // 查询待审核商家数量
            String pendingMerchantSql = "SELECT COUNT(*) FROM tb_merchant WHERE status = 0";
            Integer pendingMerchantCount = jdbcTemplate.queryForObject(pendingMerchantSql, Integer.class);
            data.put("pendingMerchantCount", pendingMerchantCount);
            
            // 查询骑手总数
            String riderSql = "SELECT COUNT(*) FROM tb_rider";
            Integer riderCount = jdbcTemplate.queryForObject(riderSql, Integer.class);
            data.put("riderCount", riderCount);
            
            // 查询待审核骑手数量
            String pendingRiderSql = "SELECT COUNT(*) FROM tb_rider WHERE status = 0";
            Integer pendingRiderCount = jdbcTemplate.queryForObject(pendingRiderSql, Integer.class);
            data.put("pendingRiderCount", pendingRiderCount);
            
            // 查询用户总数
            String userSql = "SELECT COUNT(*) FROM tb_user";
            Integer userCount = jdbcTemplate.queryForObject(userSql, Integer.class);
            data.put("userCount", userCount);
            
            // 查询平台总收入
            String revenueSql = "SELECT IFNULL(SUM(pay_amount), 0) FROM tb_order WHERE status >= 1";
            Double totalRevenue = jdbcTemplate.queryForObject(revenueSql, Double.class);
            data.put("totalRevenue", totalRevenue);
            
            // 查询近7天订单统计
            List<Map<String, Object>> orderStats = new ArrayList<>();
            
            String orderStatsSql = "SELECT DATE_FORMAT(created_time, '%Y-%m-%d') as date, " +
                                  "COUNT(*) as orderCount, " +
                                  "IFNULL(SUM(pay_amount), 0) as amount " +
                                  "FROM tb_order " +
                                  "WHERE created_time >= DATE_SUB(CURDATE(), INTERVAL 6 DAY) " +
                                  "GROUP BY DATE_FORMAT(created_time, '%Y-%m-%d') " +
                                  "ORDER BY date ASC";
            
            List<Map<String, Object>> dbOrderStats = jdbcTemplate.queryForList(orderStatsSql);
            
            // 确保有7天的数据（即使某天没有订单）
            Map<String, Map<String, Object>> dateMap = new HashMap<>();
            Calendar calendar = Calendar.getInstance();
            
            // 初始化过去7天的日期
            for (int i = 6; i >= 0; i--) {
                Calendar tempCal = (Calendar) calendar.clone();
                tempCal.add(Calendar.DAY_OF_MONTH, -i);
                
                String dateStr = String.format("%d-%02d-%02d", 
                    tempCal.get(Calendar.YEAR), 
                    tempCal.get(Calendar.MONTH) + 1, 
                    tempCal.get(Calendar.DAY_OF_MONTH));
                
                Map<String, Object> dayStat = new HashMap<>();
                dayStat.put("date", dateStr);
                dayStat.put("orderCount", 0);
                dayStat.put("amount", 0.0);
                
                dateMap.put(dateStr, dayStat);
            }
            
            // 填充数据库查询结果
            for (Map<String, Object> stat : dbOrderStats) {
                String date = (String) stat.get("date");
                if (dateMap.containsKey(date)) {
                    dateMap.put(date, stat);
                }
            }
            
            // 按日期排序并添加到结果列表
            calendar = Calendar.getInstance();
            for (int i = 6; i >= 0; i--) {
                Calendar tempCal = (Calendar) calendar.clone();
                tempCal.add(Calendar.DAY_OF_MONTH, -i);
                
                String dateStr = String.format("%d-%02d-%02d", 
                    tempCal.get(Calendar.YEAR), 
                    tempCal.get(Calendar.MONTH) + 1, 
                    tempCal.get(Calendar.DAY_OF_MONTH));
                
                orderStats.add(dateMap.get(dateStr));
            }
            
            data.put("orderStats", orderStats);
            
        } catch (Exception e) {
            e.printStackTrace();
            // 如果查询失败，使用模拟数据作为备份
            data.put("merchantCount", 120);
            data.put("riderCount", 85);
            data.put("userCount", 1350);
            data.put("totalRevenue", 27500.50);
            data.put("pendingMerchantCount", 12);
            data.put("pendingRiderCount", 8);
            
            // 近7日订单统计（备份数据）
            List<Map<String, Object>> orderStats = new ArrayList<>();
            Calendar calendar = Calendar.getInstance();
            for (int i = 6; i >= 0; i--) {
                Calendar tempCal = (Calendar) calendar.clone();
                tempCal.add(Calendar.DAY_OF_MONTH, -i);
                
                Map<String, Object> dayStat = new HashMap<>();
                dayStat.put("date", String.format("%d-%02d-%02d", 
                    tempCal.get(Calendar.YEAR), 
                    tempCal.get(Calendar.MONTH) + 1, 
                    tempCal.get(Calendar.DAY_OF_MONTH)));
                dayStat.put("orderCount", 50 + new Random().nextInt(100));
                dayStat.put("amount", 2000 + new Random().nextInt(5000));
                
                orderStats.add(dayStat);
            }
            data.put("orderStats", orderStats);
        }
        
        return data;
    }
} 